﻿using NetWorkToolkit;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[SerializeField]
public struct ModulePose
{
    public Vector3 pos;
    public Quaternion rot;
    public string mid;

    public void SetData(Vector3 _pos, Quaternion _rot, string _mid)
    {
        pos = _pos;
        rot = _rot;
        mid = _mid;
    }
}

[SerializeField]
public struct AllModulePose
{
    public ModulePose[] modules;
}

public class NetSyncModule : MonoBehaviour
{
    public string ModuleId;
    public bool AllowCompete = false;
    [Space(20)]
    public string BelongId = "0";
    public bool holdon { get; set; }

    public void SetData(string belongid = "0", bool hold = false)
    {
        BelongId = belongid;
        holdon = hold;
    }

    bool going = false;
    bool runOnce = false;
    bool isRemove = false;
    public void SetSync(bool sync = false, bool remove = false)
    {
        going = sync;
        isRemove = remove;
        if (sync && !runOnce)
        {
            runOnce = true;
            ClientUpdator.Instance.StartCoroutine(SyncRun());
        }
        else
        {
            runOnce = false;
            ClientUpdator.Instance.StopCoroutine(SyncRun());
        }
    }
    private IEnumerator SyncRun()
    {
        while (true)
        {
            if (!going && !isRemove)
            {
                going = true;
                MessageManager.Instance.SendC2SUploadANetSyncModuleInfo(transform.position, transform.rotation, ModuleId, "0");
                yield break;
            }
            yield return new WaitForSeconds(1f / 30);
            if (!isRemove)
                MessageManager.Instance.SendC2SUploadANetSyncModuleInfo(transform.position, transform.rotation, ModuleId, ColyseusClient.instance.SessionID);
        }
    }
    ModulePose mp = new ModulePose();
    private ModulePose GetModulePose()
    {
        mp.SetData(transform.position, transform.rotation, ModuleId);
        return mp;
    }

    public void SetDataFromServerData(string belongid, double[] pose)
    {
        BelongId = belongid;

        if (belongid.Equals("0"))
        {
            return;
        }
        if (belongid.Equals(ColyseusClient.instance.SessionID))
        {
            return;
        }
        this.transform.position = new Vector3((float)pose[0], (float)pose[1], (float)pose[2]);
        this.transform.rotation = new Quaternion((float)pose[3], (float)pose[4], (float)pose[5], (float)pose[6]);
    }

}
